// 引入刚刚在建立连接mysql数据库的db.js文件
const db = require('../config/db');
const log= require('../middleware/log4j')

// 引入Sequelize对象
const Sequelize = db.sequelize;
// 引入上一步的数据表模型文件
const mChecktime = Sequelize.import('../schema/checktime');
// 自动创建表
mChecktime.sync({force: false});

class checktimemodules {
    /**
     * 创建模型
     * @param data
     * @returns {Promise<*>}
     */
    static async createCheckTime(data) {
        //console.log(data);
        return await mChecktime.create({
            userid: "", 
            DEFAULTDEPTID: data.DEFAULTDEPTID, 
            Name: data.Name, 
            PIN: data.PIN,
            CHECKTIME:data.CHECKTIME,
            SENSORID:data.SENSORID,
            SSN:data.SSN,
            verifycode:data.verifycode,
            CardNo:data.CardNo
        }).catch(e=>{ console.log(e);})
    }
    /**批量增加 */
    static async createCheckTimes(data) {
        //console.log(data);
        return await mChecktime.bulkCreate(data,{ignoreDuplicates:true}).then(res=>{
            // log.info(`异常： ${JSON.stringify(res)}`) 
        })
    }
    /**根据姓名查询打卡记录 */
    static async  getUserByUserName(name,start,end){
        //console.log("object");
        return await mChecktime.findAll({
            attributes:{exclude:['userid']},
            where:{
                Name:name,
                CHECKTIME:{
                    $between: [start, end]
                }
            }
        });
    }
    /**根据工号SSN码查询打卡记录 */
    static async  getUserByLoginName(name,start,end){
        //console.log("object");
        return await mChecktime.findAll({
            attributes:{exclude:['userid']},
            where:{
                SSN:name,
                CHECKTIME:{
                    $between: [start, end]
                }
            }
        });
    }
    /**获取表中记录条数 */
    static async  getCount(){
        //console.log("object");
        return await mChecktime.findAndCountAll({attributes:{include:['id']}});
    }
    //获得最新的数据
    static async getlast(){
        try {
            //Sequelize.query('SELECT updatedAt FROM leave_table ORDER BY id DESC LIMIT 1').then(res=>{console.log(JSON.stringify(res));})
            return await mChecktime.findAll({limit:1, order:Sequelize.literal('id DESC'),attributes:{include:['updatedAt']}});
        } catch (error) {
            console.log(error);
        }
    }
}

module.exports = checktimemodules